package com.example.demo.controller;

import com.example.demo.model.Author;
import com.example.demo.repository.JdbcRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/jdbc/author")
public class JdbcController {

    @Autowired
    private JdbcRepository jdbcRepository;

    @GetMapping("/all")
    public List<Author> getAllAuthors() {
        return jdbcRepository.getAllAuthors();
    }

    @PostMapping("/add")
    public Author getAuthorById(@RequestBody Author author) {
        return jdbcRepository.insertAuthor(author);
    }


    @PutMapping("/update")
    public ResponseEntity<Author> updateAuthorById(@RequestBody Author author) {
         int result = jdbcRepository.updateAuthor(author);
         System.out.println(result);
         return ResponseEntity.ok(author);
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Integer> deleteAuthorById(@PathVariable("id") Long id) {
        return ResponseEntity.ok(jdbcRepository.deleteAuthor(id));
    }

    @GetMapping("/filter/{name}")
    public ResponseEntity<List<Author>> getAllAuthorsByName(@PathVariable("name") String name) {
        System.out.println(name);
        List<Author> authors = jdbcRepository.getAllAuthorsByName(name);
        return ResponseEntity.ok(authors);
    }
}
